package com.hxzy.servlet.servletContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author nick
 */
@WebServlet("/online")
public class OnlineCustomerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        int onlineCount = 1;

        //获取服务器在线人数
        ServletContext servletContext = req.getServletContext();
        Object count = servletContext.getAttribute("count");
        if (count == null) { //第一次访问时，application作用域中没有统计在线人数
            servletContext.setAttribute("count", onlineCount);
        } else { //已经统计了在线人数
            int online = (int) count;
            if (session.isNew()) {//如果session是最近创建的，说明是刚上线的用户
                servletContext.setAttribute("count",++online);//累加
            }
            onlineCount = online;
        }

        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("当前在线人数" + onlineCount);

        writer.close();
    }
}
